import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Select, Popconfirm, Input, Badge, Breadcrumb } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import styles from '../../../global.less';
import { queryRule, updateRule, addRule, removeRule, getAction, getActionField } from './service';
import ControlledInput from './components/ControlledInput';
import FormItem from 'antd/lib/form/FormItem';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields, actionRef) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    actionRef.current.reload();

    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const { Option } = Select;
const { TextArea } = Input;

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const formRef = useRef();
  const [module, setModule] = useState();
  const [count, setCount] = useState();
  const [variable, setVariable] = useState([]);
  const [contentVal, setContentVal] = useState('');
  const [variableVal, setVariableVal] = useState('');
  const [actionData, setActionData] = useState([]);
  const handleAttribute = (e, key) => {
    const val = key.children;
    setVariableVal(val);
    setContentVal(contentVal + '{' + val + '}');
  };
  const handleContent = (e) => {
    setContentVal(e.target.value);
    if (variableVal !== '') {
      setVariableVal('');
    } else {
      return;
    }
  };
  const handleGetAction = () => {
    getAction().then((res) => {
      if (res.code === 0) {
        const {
          data: { list },
        } = res;
        setActionData(list);
      }
    });
  };
  const onChangeAction = (payload, key) => {
    getActionField(key.value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setVariable(data);
      }
    });
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标题为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a onClick={() => setRow(entity)}>{dom}</a>;
      },
    },
    {
      title: '所属行为',
      dataIndex: 'actionId',
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标题为必填项',
          },
        ],
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem name="actionId" label={null} className="formItem_div">
            <Select placeholder="请选择所属行为" onSelect={onChangeAction}>
              {actionData.map((item_, index) => {
                return (
                  <Option value={item_.id} key={index}>
                    {item_.name}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '选择属性',
      dataIndex: 'select',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            <Select placeholder="请选择属性" value={variableVal} onChange={handleAttribute}>
              {variable.map((item_, index) => {
                return (
                  <Option value={item_.id} key={index}>
                    {item_.name}
                  </Option>
                );
              })}
            </Select>
          </>
        );
      },
    },
    {
      title: '内容',
      dataIndex: 'content',
      valueType: 'text',
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <ControlledInput
            value={contentVal}
            placeholder="请输入模板内容"
            allowClear
            onChange={handleContent}
          />
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                handleModalVisible(true);
                handleUpdateModalVisible(true);
                setContentVal(record.content);
                setStepFormValues(record);
              }}
            >
              修改
            </a>

            <Divider type="vertical" />

            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a onClick={() => {}}>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="短信模板表格"
        actionRef={actionRef}
        rowKey="id"
        bordered
        formRef={formRef}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleUpdateModalVisible(false);
              handleModalVisible(true);
              setContentVal('');
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          handleGetAction();
          setCount(total);
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />

      <CreateForm
        width={800}
        title={updateModalVisible ? '修改短信模板' : '新增短信模板'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formBottom}
          onSubmit={async (value) => {
            value.content = contentVal;
            updateModalVisible ? (value.id = stepFormValues.id) : null;
            const success = updateModalVisible
              ? await handleUpdate(value, actionRef)
              : await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updateModalVisible === true ? stepFormValues : '',
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
